import {
  WS_URL
} from "@/api/index.js";


// 断线重连次数
const DISCONNECTION_RECONNECTS_NUM = 3;
// 断线重连间隔时长 单位毫秒  [3秒]
const DISCONNECTION_RECONNECTS_TIME = 3000;
// 断线重连尝试剩余次数
let disconnection_reconnects_try_num = DISCONNECTION_RECONNECTS_NUM;

// socketTask 对象
let socketTask = null;

export default {
  launch(APP) {
    this.APP = APP;
    this.handleInitWebsocket();
    uni.$on("message-socket", () => {
      this.handleInitWebsocket();
    });
    uni.$on("message-socket-end", () => {
      this.handleCloseWebsocket();
    });
  },
  // --------------------------------
  // 初始化websocket
  handleInitWebsocket() {
    if (!this.APP.globalData.login) {
      // 未登录
      return;
    }

    let token = this.APP.globalData.getUser().token;
    // 创建一个 socketTask对象
    socketTask = uni.connectSocket({
      url: WS_URL + token,
      success: data => {
        disconnection_reconnects_try_num = DISCONNECTION_RECONNECTS_NUM;
      },
      fail: () => {
        console.log("fail");
        this.handleReconnect()
      }
    });
    // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
    socketTask.onOpen(res => {
      console.log("WebSocket连接正常打开中...！");
      socketTask.onMessage(res => {
        this.hanldeMessage(res.data);
      });
    });
    socketTask.onError(() => {
      console.log("onError");
      this.handleReconnect();
    })
  },
  // 处理消息
  hanldeMessage(data) {
    try {
      data = JSON.parse(data);
    } catch (e) {
      // 返回的数据未能正常解析 不做任何处理
      return;
    }
    switch (data.type) {
      case "UnreadMessages":
        if (data.msgNum > 0) {
          uni.setTabBarBadge({
            index: 2,
            text: data.msgNum > 99 ? "99+" : String(data.msgNum),
          });
        } else {
          uni.removeTabBarBadge({
            index: 2,
          });
        }
        break;
      default:
        break;
    }
  },
  // 断开连接
  handleCloseWebsocket() {
    socketTask && socketTask.close();
  },
  // 断线重连
  handleReconnect() {
    setTimeout(() => {
      if (disconnection_reconnects_try_num == 0) {
        return;
      }
      disconnection_reconnects_try_num--;
      this.handleInitWebsocket();
    }, DISCONNECTION_RECONNECTS_TIME);
  }
}
